(() => {
  const body = document.body;
  if (!body) return;
  const pageKey = body.dataset.page;
  if (!pageKey || pageKey === 'home') return;

  const root = document.querySelector('[data-page-root]') || document.querySelector('main');
  if (!root) return;

  const params = new URLSearchParams(window.location.search);
  const previewToken = params.get('preview') || '';
  let mode = params.get('mode') === 'draft' ? 'draft' : 'published';
  if (previewToken && !params.get('mode')) {
    mode = 'draft';
  }
  const requestParams = new URLSearchParams();
  if (mode === 'draft') requestParams.set('mode', 'draft');
  if (previewToken) requestParams.set('preview', previewToken);
  if (params.has('refresh')) requestParams.set('refresh', '1');
  const queryString = requestParams.toString();
  const url = `/api/content/${pageKey}${queryString ? `?${queryString}` : ''}`;

  fetch(url, { cache: 'no-store' })
    .then((res) => {
      if (!res.ok) throw new Error(`无法加载 ${pageKey} 页面内容`);
      return res.json();
    })
    .then((payload) => renderPage(root, payload || {}))
    .catch((err) => {
      console.error('[PageContent]', err);
      root.innerHTML = `<section class="section"><div class="container"><p class="muted">页面内容加载失败：${escapeHtml(
        err.message || String(err)
      )}</p></div></section>`;
    });
})();

function renderPage(root, payload) {
  const content = payload?.content || {};
  const meta = payload?.meta || {};
  const references = payload?.references || {};
  const site = payload?.site || {};

  root.innerHTML = '';
  root.dataset.renderMode = payload.mode || 'published';
  if (payload.cache) {
    root.dataset.cacheHit = payload.cache.hit ? '1' : '0';
  } else {
    delete root.dataset.cacheHit;
  }

  const hero = enrichHero(content.hero || {}, references, meta);
  hero.media = normalizeMedia(hero.media);

  applyDocumentMeta(meta, site, hero);

  const fragment = document.createDocumentFragment();
  if (hasHeroContent(hero)) {
    fragment.appendChild(renderHero(hero));
  }

  const sections = Array.isArray(content.sections) ? content.sections : [];
  sections.forEach((section) => {
    const el = renderSection(section);
    if (el) fragment.appendChild(el);
  });

  if (!fragment.childNodes.length) {
    fragment.appendChild(renderEmptyState());
  }

  root.appendChild(fragment);
}

function applyDocumentMeta(meta, site, hero) {
  if (!meta && !hero) return;
  const fallbackSummary =
    meta?.summary ||
    hero?.summary ||
    hero?.lead ||
    hero?.description ||
    (Array.isArray(hero?.meta) && hero.meta.length ? hero.meta[0] : '');
  const titleSource = meta?.title || hero?.title || hero?.eyebrow || '';
  if (titleSource) {
    const suffix = site?.companyName;
    document.title = suffix ? `${titleSource} · ${suffix}` : titleSource;
  }
  if (fallbackSummary) {
    setMetaTag('description', fallbackSummary);
  }
}

function setMetaTag(name, content) {
  if (!name || !content) return;
  let tag = document.querySelector(`meta[name="${name}"]`);
  if (!tag) {
    tag = document.createElement('meta');
    tag.setAttribute('name', name);
    document.head.appendChild(tag);
  }
  tag.setAttribute('content', content);
}

function enrichHero(hero, references, meta) {
  const enriched = Object.assign({}, hero);
  const cube = references?.cubeFace;
  if (cube) {
    if (!enriched.title && cube.label) enriched.title = cube.label;
    if (!enriched.subtitle && cube.subtitle) enriched.subtitle = cube.subtitle;
    if (!enriched.lead && cube.description) enriched.lead = cube.description;
    if (!enriched.summary && cube.summary) enriched.summary = cube.summary;
    if (!enriched.cta && cube.cta) enriched.cta = cube.cta;
  }
  const nav = references?.navigation;
  if (nav && !enriched.summary && nav.summary) {
    enriched.summary = nav.summary;
  }
  if (meta) {
    if (!enriched.title && meta.title) {
      enriched.title = meta.title;
    }
    if (!enriched.lead && meta.summary) {
      enriched.lead = meta.summary;
    }
    if (!enriched.media && meta.heroImage) {
      enriched.media = {
        type: 'image',
        src: meta.heroImage,
        alt: enriched.title || ''
      };
    }
  }
  const fallbackTitle = meta?.title || cube?.label || nav?.label || enriched.title || enriched.eyebrow || '';
  if (fallbackTitle) {
    enriched.pageTitle = fallbackTitle;
  }
  return enriched;
}

function hasHeroContent(hero) {
  if (!hero) return false;
  return Boolean(
    hero.title ||
      hero.subtitle ||
      hero.lead ||
      hero.description ||
      hero.summary ||
      hero.media ||
      (Array.isArray(hero.meta) && hero.meta.length) ||
      (Array.isArray(hero.metrics) && hero.metrics.length)
  );
}

function normalizeMedia(media) {
  if (!media || typeof media !== 'object') return null;
  const src = resolveAssetUrl(media.src);
  if (!src) return null;
  const type = media.type === 'video' ? 'video' : 'image';
  return Object.assign({}, media, { type, src });
}

function renderHero(hero) {
  const section = document.createElement('section');
  section.className = 'page-hero';
  const media = hero.media && typeof hero.media === 'object' ? hero.media : null;
  const hasMedia = Boolean(media);
  section.innerHTML = `
    <div class="container page-hero__layout${hasMedia ? ' page-hero__layout--split' : ''}">
      <div class="page-hero__content">
        ${
          hero.pageTitle && hero.pageTitle !== hero.title
            ? `<p class="page-hero__page-title">${escapeHtml(hero.pageTitle)}</p>`
            : ''
        }
        ${hero.badge ? `<span class="page-hero__badge">${escapeHtml(hero.badge)}</span>` : ''}
        ${hero.eyebrow ? `<span class="page-hero__eyebrow">${escapeHtml(hero.eyebrow)}</span>` : ''}
        ${hero.title ? `<h1 class="page-hero__title">${escapeHtml(hero.title)}</h1>` : ''}
        ${hero.subtitle ? `<p class="page-hero__subtitle">${escapeHtml(hero.subtitle)}</p>` : ''}
        ${hero.lead ? `<p class="page-hero__lead">${escapeHtml(hero.lead)}</p>` : ''}
        ${hero.description ? `<p class="page-hero__description">${escapeHtml(hero.description)}</p>` : ''}
        ${hero.summary ? `<p class="page-hero__summary">${escapeHtml(hero.summary)}</p>` : ''}
        ${
          Array.isArray(hero.meta) && hero.meta.length
            ? `<div class="page-hero__meta">${hero.meta.map((item) => `<span>${escapeHtml(item)}</span>`).join('')}</div>`
            : ''
        }
        ${renderHeroMetrics(hero.metrics)}
        ${renderActionGroup(hero.actions, hero.cta)}
      </div>
      ${renderHeroMedia(media)}
    </div>
  `;
  return section;
}

function renderHeroMedia(media) {
  if (!media || !media.src) return '';
  if (media.type === 'video') {
    const attrs = [
      `src="${escapeAttr(media.src)}"`,
      media.poster ? `poster="${escapeAttr(media.poster)}"` : '',
      'playsinline',
      'muted',
      'loop',
      'autoplay'
    ]
      .filter(Boolean)
      .join(' ');
    return `
      <div class="page-hero__media">
        <video ${attrs}></video>
        ${media.caption ? `<p class="media-caption">${escapeHtml(media.caption)}</p>` : ''}
      </div>
    `;
  }
  return `
    <div class="page-hero__media">
      <img src="${escapeAttr(media.src)}" alt="${escapeAttr(media.alt || '')}" loading="lazy" />
      ${media.caption ? `<p class="media-caption">${escapeHtml(media.caption)}</p>` : ''}
    </div>
  `;
}

function renderHeroMetrics(metrics) {
  if (!Array.isArray(metrics) || !metrics.length) return '';
  const items = metrics
    .map((metric) => {
      const value = metric?.value ? `<div class="metric__value">${escapeHtml(metric.value)}</div>` : '';
      const label = metric?.label ? `<div class="metric__label">${escapeHtml(metric.label)}</div>` : '';
      const description = metric?.description
        ? `<p class="metric__description">${escapeHtml(metric.description)}</p>`
        : '';
      if (!value && !label && !description) return '';
      return `<div class="metric">${value}${label}${description}</div>`;
    })
    .filter(Boolean)
    .join('');
  if (!items) return '';
  return `<div class="page-hero__metrics">${items}</div>`;
}

function renderActionGroup(actions, cta) {
  const list = Array.isArray(actions) ? actions.filter(Boolean) : [];
  if (cta) list.push(cta);
  if (!list.length) return '';
  return `
    <div class="page-actions">
      ${list
        .map((action, index) => renderAction(action, index === 0 ? 'primary' : 'secondary'))
        .filter(Boolean)
        .join('')}
    </div>
  `;
}

function renderAction(action, variant = 'primary') {
  if (!action || typeof action !== 'object') return '';
  const label = action.label ? escapeHtml(action.label) : '';
  const href = action.href ? escapeAttr(action.href) : '#';
  if (!label) return '';
  const target = action.target === '_blank' ? ' target="_blank" rel="noopener noreferrer"' : '';
  return `<a class="button button--${variant}" href="${href}"${target}>${label}</a>`;
}

function renderSection(section) {
  const type = section?.type || '';
  switch (type) {
    case 'cards':
      return renderCardsSection(section);
    case 'timeline':
      return renderTimelineSection(section);
    case 'stats':
      return renderStatsSection(section);
    case 'list':
      return renderListSection(section);
    case 'contact':
      return renderContactSection(section);
    case 'gallery':
      return renderGallerySection(section);
    case 'richtext':
      return renderRichtextSection(section);
    default:
      return renderBasicSection(section);
  }
}

function renderSectionHead(section) {
  const title = section.title ? `<h2 class="section__title">${escapeHtml(section.title)}</h2>` : '';
  const subtitle = section.subtitle ? `<p class="section__subtitle">${escapeHtml(section.subtitle)}</p>` : '';
  const description = section.description
    ? `<p class="section__description">${escapeHtml(section.description)}</p>`
    : '';
  if (!title && !subtitle && !description) return '';
  return `<div class="section__head">${title}${subtitle}${description}</div>`;
}

function renderSectionFooter(section) {
  if (!section?.cta) return '';
  const action = renderAction(section.cta, 'secondary');
  if (!action) return '';
  return `<div class="section__footer">${action}</div>`;
}

function renderCardsSection(section) {
  const cards = Array.isArray(section.cards) ? section.cards : [];
  const content = cards
    .map((card) => {
      const media = normalizeMedia(card.media);
      const badge = card.badge ? `<span class="badge">${escapeHtml(card.badge)}</span>` : '';
      const title = card.title ? `<h3 class="card__title">${escapeHtml(card.title)}</h3>` : '';
      const subtitle = card.subtitle ? `<p class="card__subtitle">${escapeHtml(card.subtitle)}</p>` : '';
      const description = card.description ? `<p class="card__meta">${escapeHtml(card.description)}</p>` : '';
      const mediaHtml = media
        ? `<div class="card__media"><img src="${escapeAttr(media.src)}" alt="${escapeAttr(
            media.alt || card.title || ''
          )}" loading="lazy" /></div>`
        : '';
      const actions =
        Array.isArray(card.actions) && card.actions.length
          ? `<div class="card__actions">${card.actions.map((action) => renderAction(action, 'secondary')).join('')}</div>`
          : '';
      return `<article class="card">${badge}${mediaHtml}${title}${subtitle}${description}${actions}</article>`;
    })
    .join('');
  const sectionEl = document.createElement('section');
  sectionEl.className = `section${section.tint ? ' section--tinted' : ''}`;
  sectionEl.innerHTML = `
    <div class="container">
      ${renderSectionHead(section)}
      <div class="card-grid">${content}</div>
      ${renderSectionFooter(section)}
    </div>
  `;
  return sectionEl;
}

function renderTimelineSection(section) {
  const items = Array.isArray(section.items) ? section.items : [];
  const content = items
    .map((item) => {
      const year = item.year ? `<div class="timeline__year">${escapeHtml(item.year)}</div>` : '';
      const title = item.title ? `<h3 class="timeline__title">${escapeHtml(item.title)}</h3>` : '';
      const description = item.description
        ? `<p class="timeline__description">${escapeHtml(item.description)}</p>`
        : '';
      return `<div class="timeline__item">${year}${title}${description}</div>`;
    })
    .join('');
  const sectionEl = document.createElement('section');
  sectionEl.className = `section${section.tint ? ' section--tinted' : ''}`;
  sectionEl.innerHTML = `
    <div class="container">
      ${renderSectionHead(section)}
      <div class="timeline">${content}</div>
      ${renderSectionFooter(section)}
    </div>
  `;
  return sectionEl;
}

function renderStatsSection(section) {
  const stats = Array.isArray(section.stats) ? section.stats : [];
  const content = stats
    .map((item) => {
      const value = item.value ? `<div class="stat__value">${escapeHtml(item.value)}</div>` : '';
      const label = item.label ? `<div class="stat__label">${escapeHtml(item.label)}</div>` : '';
      const description = item.description
        ? `<p class="stat__description">${escapeHtml(item.description)}</p>`
        : '';
      return `<div class="stat">${value}${label}${description}</div>`;
    })
    .join('');
  const sectionEl = document.createElement('section');
  sectionEl.className = `section${section.tint ? ' section--tinted' : ''}`;
  sectionEl.innerHTML = `
    <div class="container">
      ${renderSectionHead(section)}
      <div class="stats-grid">${content}</div>
      ${renderSectionFooter(section)}
    </div>
  `;
  return sectionEl;
}

function renderListSection(section) {
  const items = Array.isArray(section.items) ? section.items : [];
  const content = items
    .map((item) => {
      const title = item.title ? `<h3 class="list-grid__title">${escapeHtml(item.title)}</h3>` : '';
      const description = item.description ? `<p class="list-grid__text">${escapeHtml(item.description)}</p>` : '';
      return `<div class="list-grid__item">${title}${description}</div>`;
    })
    .join('');
  const sectionEl = document.createElement('section');
  sectionEl.className = `section${section.tint ? ' section--tinted' : ''}`;
  sectionEl.innerHTML = `
    <div class="container">
      ${renderSectionHead(section)}
      <div class="list-grid">${content}</div>
      ${renderSectionFooter(section)}
    </div>
  `;
  return sectionEl;
}

function renderContactSection(section) {
  const items = Array.isArray(section.items) ? section.items : [];
  const content = items
    .map(
      (item) => `
        <div class="contact-list__item">
          <span class="contact-list__label">${escapeHtml(item.label || '')}</span>
          <span>${escapeHtml(item.value || '')}</span>
        </div>
      `
    )
    .join('');
  const sectionEl = document.createElement('section');
  sectionEl.className = `section${section.tint ? ' section--tinted' : ''}`;
  sectionEl.innerHTML = `
    <div class="container">
      ${renderSectionHead(section)}
      <div class="contact-panel">
        <div class="contact-list">${content}</div>
        ${section.note ? `<p class="section__description">${escapeHtml(section.note)}</p>` : ''}
      </div>
      ${renderSectionFooter(section)}
    </div>
  `;
  return sectionEl;
}

function renderGallerySection(section) {
  const items = Array.isArray(section.items) ? section.items : [];
  const content = items
    .map((item) => {
      const src = resolveAssetUrl(item.src);
      if (!src) return '';
      const alt = escapeAttr(item.alt || '');
      const caption = item.caption ? `<figcaption>${escapeHtml(item.caption)}</figcaption>` : '';
      return `<figure class="gallery__item"><img src="${src}" alt="${alt}" loading="lazy" />${caption}</figure>`;
    })
    .filter(Boolean)
    .join('');
  const sectionEl = document.createElement('section');
  sectionEl.className = `section${section.tint ? ' section--tinted' : ''}`;
  sectionEl.innerHTML = `
    <div class="container">
      ${renderSectionHead(section)}
      <div class="gallery">${content}</div>
      ${renderSectionFooter(section)}
    </div>
  `;
  return sectionEl;
}

function renderRichtextSection(section) {
  const html = section.html ? section.html : '';
  const sectionEl = document.createElement('section');
  sectionEl.className = `section${section.tint ? ' section--tinted' : ''}`;
  sectionEl.innerHTML = `
    <div class="container">
      ${renderSectionHead(section)}
      <div class="richtext">${html}</div>
      ${renderSectionFooter(section)}
    </div>
  `;
  return sectionEl;
}

function renderBasicSection(section) {
  if (!section || (!section.title && !section.description)) return null;
  const sectionEl = document.createElement('section');
  sectionEl.className = `section${section.tint ? ' section--tinted' : ''}`;
  sectionEl.innerHTML = `
    <div class="container">
      ${renderSectionHead(section)}
      ${renderSectionFooter(section)}
    </div>
  `;
  return sectionEl;
}

function renderEmptyState() {
  const section = document.createElement('section');
  section.className = 'section section--tinted';
  section.innerHTML = `
    <div class="container">
      <p class="muted">暂无页面内容，请联系管理员配置。</p>
    </div>
  `;
  return section;
}

function resolveAssetUrl(value) {
  if (!value) return '';
  const str = String(value).trim();
  if (!str) return '';
  if (/^https?:\/\//i.test(str) || str.startsWith('//')) return str;
  if (str.startsWith('/')) return str;
  return `/${str.replace(/^\/+/, '')}`;
}

function escapeHtml(str) {
  return String(str ?? '')
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');
}

function escapeAttr(str) {
  return escapeHtml(str).replace(/`/g, '&#96;');
}
